package endcourseproject;

import lejos.nxt.I2CPort;
import lejos.nxt.LCD;

public class ZTCMsg {

	public static final int MAX_MSG_SIZE = 160;
	private byte opcodeGroup; 
	private byte opcode; 
	private int len; 
	private byte[] data;

	public ZTCMsg(byte opcodeGroup, byte opcode, int len, byte[] payload )
	{
		setOpcodeGroup(opcodeGroup); 
		setOpcode(opcode); 
		setLen(len); 
		setData(payload);
	}

	public ZTCMsg()
	{
		this((byte)0,(byte)0,0,null);
	}
	
	/**
	 * @return the opcodeGroup
	 */
	public byte getOpcodeGroup() {
		return opcodeGroup;
	}

	/**
	 * @param opcodeGroup the opcodeGroup to set
	 */
	public void setOpcodeGroup(byte opcodeGroup) {
		this.opcodeGroup = opcodeGroup;
	}

	/**
	 * @return the opcode
	 */
	public byte getOpcode() {
		return opcode;
	}

	/**
	 * @param opcode the opcode to set
	 */
	public void setOpcode(byte opcode) {
		this.opcode = opcode;
	}

	/**
	 * @return the len
	 */
	public int getLen() {
		return len;
	}

	/**
	 * @param len the len to set
	 */
	public void setLen(int len) {
		this.len = len;
	}

	/**
	 * @return the data
	 */
	public byte[] getData() {
		return data;
	}

	/**
	 * @param data the data to set
	 */
	public void setData(byte[] data) {
		this.data = data;
	}

	public byte CalcCS()
	{
        byte cs = 0;
        cs ^= opcodeGroup;
        cs ^= opcode;
        cs ^= len;
        
		if(data != null && data.length >= len)
		{
    		for (int i = 0; i < len; ++i) 
    		{
    		  cs ^= data[i];
    		}
		}
		return cs;
	}
	
	public boolean VerifyCS(byte cs)
	{
 		LCD.drawString("VerifyCS 1    ", 0, 7);

		cs ^= CalcCS();
		LCD.drawString("VerifyCS 2    ", 0, 7);
		return (cs == 0);
	}

}
